function varargout = iProcessVideo(varargin)
% IPROCESSVIDEO M-file for iProcessVideo.fig
%      IPROCESSVIDEO, by itself, creates a new IPROCESSVIDEO or raises the existing
%      singleton*.
%
%      H = IPROCESSVIDEO returns the handle to a new IPROCESSVIDEO or the handle to
%      the existing singleton*.
%
%      IPROCESSVIDEO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in IPROCESSVIDEO.M with the given input arguments.
%
%      IPROCESSVIDEO('Property','Value',...) creates a new IPROCESSVIDEO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before iProcessVideo_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to iProcessVideo_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help iProcessVideo

% Last Modified by GUIDE v2.5 17-Sep-2012 19:19:31

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @iProcessVideo_OpeningFcn, ...
                   'gui_OutputFcn',  @iProcessVideo_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT






function OnOpen(handles)


global ncurrentframe;
global totalframes;
global v;

global detectareasfile;
global detectareasfilefull;

global backgroundfilefull;
global bFrontView;

global calibsubtractfilefrontfull;
global calibsubtractfilesidefull;

global configfilefull;

global inputfilefull;
global outputfilefull;

global detectareasfilefull;

global bFrontView;


global nDrawFrameSelect;
global nDrawEveryFrames;

global selecttypesfile;
global savefile;


global fdetectobjects;
global fpostprocess;
global fsegmentation;
global fassign;
global fdetectareas;
global fgenders;
global fareaspostprocess;

global scheck1;
global scheck2;
global scheck3;
global scheck4;
global scheck5;
global scheck6;
global scheck7;



outputfilefull = '';
inputfilefull = '';

detectareasfile = '';
detectareasfilefull = '';
configfilefull = '';
backgroundfilefull = '';

calibsubtractfilefrontfull = '';
calibsubtractfilesidefull = '';
bFrontView = -1;

nDrawFrameSelect = 0;
nDrawEveryFrames = 100;


savefile = 'videoprocessdata.mat';
load(savefile);


if isempty(inputfilefull)
    errordlg('The inputfilefull variable in videoprocessdata.mat is empty. Please check that an input file was selected before opening this dialog.');
    return
end

if isempty(outputfilefull)
    a = strfind(inputfilefull, '.');
    
    outputfilefull = strcat(inputfilefull(1:a), '.mat');
end



scheckfile = dir(inputfilefull);

if isempty(scheckfile)                   
    errordlg('Video file not found.')  
    return
end
         

flen = length(inputfilefull);
f = inputfilefull(1:flen-4);
 
fdetectobjects = strcat(f, '_detectobjects.mat'); 
fpostprocess = strcat(f, '_postprocess.mat'); 
fsegmentation = strcat(f, '_objectsegmentation.mat'); 
fassign = strcat(f, '_assignobjects.mat'); 
fdetectareas = strcat(f, '_detectareas.mat'); 
fgenders = strcat(f, '_genders.mat'); 
fareaspostprocess = strcat(f, '_detectareaspp.mat'); 


v = mmreader(inputfilefull); 
totalframes = v.NumberOfFrames;



UpdateShowDetectionButtons(handles);

bLoad = 0;

if ~isempty(scheck1)
    load(fdetectobjects)
    bLoad = 1;
elseif ~isempty(scheck2)
    load(fpostprocess)
    bLoad = 1;
elseif ~isempty(scheck3)
    load(fsegmentation)
    bLoad = 1;    
elseif ~isempty(scheck4)
    load(fassign)
    bLoad = 1;
elseif ~isempty(scheck5)
    load(fdetectareas)
    bLoad = 1;
elseif ~isempty(scheck6)
    load(fgenders)
    bLoad = 1;
elseif ~isempty(scheck7)
    load(fareaspostprocess)
    bLoad = 1;
end

ncurrentframe = 1;
nDrawFrameSelect = 0;

if bLoad == 1
    nobjects = nfindobjs;

else    
    nstartframe = ncurrentframe;
    nendframe = totalframes;
    nobjects = 2;         
end



if bFrontView == 1
    set(handles.radiobuttonfront, 'Value', 1);
    set(handles.radiobuttonside, 'Value', 0);
elseif bFrontView == 0
    set(handles.radiobuttonfront, 'Value', 0);
    set(handles.radiobuttonside, 'Value', 1);
end

if nDrawFrameSelect == 0
    set(handles.radiobuttonnoshow, 'Value', 1);
    set(handles.radiobuttondrawsquare, 'Value', 0);
    set(handles.radiobuttondrawellipse, 'Value', 0);
elseif nDrawFrameSelect == 1
    set(handles.radiobuttonnoshow, 'Value', 0);
    set(handles.radiobuttondrawsquare, 'Value', 1);
    set(handles.radiobuttondrawellipse, 'Value', 0);
else
    set(handles.radiobuttonnoshow, 'Value', 0);
    set(handles.radiobuttondrawsquare, 'Value', 0);
    set(handles.radiobuttondrawellipse, 'Value', 1);
end


set(handles.editdrawframes, 'String', num2str(nDrawEveryFrames));


set(handles.editstart, 'String', num2str(nstartframe));
set(handles.editend, 'String', num2str(nendframe));


set(handles.editvideofrom, 'String', num2str(nstartframe));
set(handles.editvideoto, 'String', num2str(nendframe));


set(handles.editframe, 'String', num2str(nstartframe));
set(handles.textframes, 'String', num2str(totalframes));

set(handles.editobjects, 'String', num2str(nobjects));


UpdateVideoProcessCheckBoxes(handles);


ButtonGotoFrame(handles)





function ButtonGotoFrame(handles)

global totalframes; 
global ncurrentframe;

scurrentframe = get(handles.editframe, 'String');
n = str2num(scurrentframe);

if n > 0 & n <= totalframes
    ncurrentframe = n;
    
    d = ncurrentframe/totalframes;
    set(handles.sliderframe, 'Value', d);
    
    GotoFrame(handles)
end


function SliderGotoFrame(handles)

global totalframes; 
global ncurrentframe;

n = get(handles.sliderframe, 'Value');
ncurrentframe = floor(totalframes*n)+1;

if ncurrentframe > totalframes
    ncurrentframe = totalframes;
end

set(handles.editframe, 'String', num2str(ncurrentframe));
GotoFrame(handles);




function GotoFrame(handles)

global ncurrentframe;
global img;
global v;
global totalframes;


global fdetectobjects;
global fpostprocess;
global fsegmentation;
global fassign;
global fdetectareas;
global fgenders;
global fareaspostprocess;

global scheck1;
global scheck2;
global scheck3;
global scheck4;
global scheck5;
global scheck6;
global scheck7;

global inputfilefull;
global savefile;

if ncurrentframe > totalframes
    ncurrentframe = totalframes;
end

if ncurrentframe <=0
    ncurrentframe = 1;
end


if isempty(v)
    
    if isempty(inputfilefull) 
        load('videoprocessdata.mat');
    end
        
    if ~isempty(inputfilefull)
        scheck = dir(inputfilefull);
        
        if ~isempty(scheck)
            v = mmreader(inputfilefull);
            totalframes = v.NumberOfFrames;
            ncurrentframe = 1;
            
            set(handles.editframe, 'String', num2str(ncurrentframe));
            set(handles.textframes, 'String', num2str(totalframes));
        end
    end
end

img = read(v,ncurrentframe);




rbnone = get(handles.radiobuttonnone, 'Value');
rbobjdetect = get(handles.radiobuttonobjectdetection,'Value');
rbpostprocess = get(handles.radiobuttonpostprocessing,'Value');
rbsegment = get(handles.radiobuttonsegementation,'Value');
rbassignobj = get(handles.radiobuttonassignobjects,'Value');

cbdetectareas = get(handles.checkboxshowdetectedareas,'Value');
cbgenderssign = get(handles.checkboxshowassigngender,'Value');
cbdetectareaspp = get(handles.checkboxshowpostprocessingareas,'Value');

rbsquares = get(handles.radiobuttondrawsquares,'Value');
rbellipses = get(handles.radiobuttondrawellipses,'Value');



if rbobjdetect == 1 & cbgenderssign == 0
    if ~isempty(scheck1)
        load(fdetectobjects);
        
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            if rbsquares == 1
                img = DrawObjectsSquares(img, vx1s, vx2s, vy1s, vy2s, objs,index);
            else
                img = DrawObjectsEllipses(img, vex0s, vey0s, vephis, veas, vebs, objs, index);
            end
        end
    end
elseif rbpostprocess == 1 & cbgenderssign == 0
    if ~isempty(scheck2)
        load(fpostprocess);
        
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            

            if rbsquares == 1
                img = DrawObjectsSquares(img, vx1s, vx2s, vy1s, vy2s, objs,index);
            else
                img = DrawObjectsEllipses(img, vex0s, vey0s, vephis, veas, vebs, objs, index);
            end
        end
    end
elseif rbsegment == 1 & cbgenderssign == 0
    if ~isempty(scheck3)
        load(fsegmentation);
        
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            if rbsquares == 1
                img = DrawObjectsSquares(img, vx1s, vx2s, vy1s, vy2s, objs,index);
            else
                img = DrawObjectsEllipses(img, vex0s, vey0s, vephis, veas, vebs, objs, index);
            end
        end
    end
elseif rbassignobj == 1 & cbgenderssign == 0
    if ~isempty(scheck4)
                      
        load(fassign);
        
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            if rbsquares == 1
                img = DrawObjectsSquares(img, x1s, x2s, y1s, y2s, objs,index);
            else
                img = DrawObjectsEllipses(img, ex0s, ey0s, ephis, eas, ebs, objs, index);                
            end
        end       
    end
elseif cbgenderssign == 1
    
    if ~isempty(scheck6) 
        load(fgenders);
        
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            if rbsquares == 1
                img = DrawGendersSquares(img, x1s, x2s, y1s, y2s, objs, gendertypes, bgenderwarnings, index);
            else
                img = DrawGendersEllipses(img, ex0s, ey0s, ephis, eas, ebs, objs, gendertypes, bgenderwarnings, index);                
            end
        end
    end
end

if cbdetectareas == 1 & cbdetectareaspp == 0 
    if ~isempty(scheck5)
        load(fdetectareas);
        load(selecttypesfilefull);
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            img = DrawAreas(img, x1s, x2s, y1s, y2s, areasx1, areasx2, areasy1, areasy2,... 
                            areascores, bestscoreindexes, bwarnings, bFemales, index);                        
        end
    end
elseif cbdetectareaspp == 1
  if ~isempty(scheck7)
        load(fareaspostprocess);
        load(selecttypesfilefull);
        if ncurrentframe >= nstartframe & ncurrentframe <= nendframe
            index = ncurrentframe-nstartframe+1;
            
            img = DrawAreas(img, x1s, x2s, y1s, y2s, areasx1, areasx2, areasy1, areasy2,... 
                            areascores, bestscoreindexes, bwarnings, bFemales, index);                        
        end
    end
end


imshow(img);


function img = DrawObjectsSquares(img, x1s, x2s, y1s, y2s, objs, index)

r = 255;
g = 255;
b = 255;
linethickness = 3;

imgsz = size(img);
xl = imgsz(1);
yl = imgsz(2);

sz = size(x1s);
len = sz(2);

for j = 1:len
    x1 = x1s(index,j);
    x2 = x2s(index,j);
    y1 = y1s(index,j);
    y2 = y2s(index,j);    
    
    if x1 > 0 & objs(index) > 0
        img = DrawThickColorRGBBox(img,  x1, y1, x2, y2, r, g, b, linethickness, xl, yl);
    end
end



function img = DrawGendersSquares(img, x1s, x2s, y1s, y2s, objs, gendertypes, bgenderwarnings, index)


linethickness = 3;

imgsz = size(img);
xl = imgsz(1);
yl = imgsz(2);

sz = size(x1s);
len = sz(2);

for j = 1:len
    x1 = x1s(index,j);
    x2 = x2s(index,j);
    y1 = y1s(index,j);
    y2 = y2s(index,j);  
    
    if gendertypes(index, j) == 0 & bgenderwarnings(index) == 0 %female
        r = 250;
        g = 110;
        b = 110;
    elseif gendertypes(index, j) == 1 & bgenderwarnings(index) == 0 %male
        r = 110;
        g = 250;
        b = 110;
    else
        r = 255;
        g = 255;
        b = 255;
    end
    
    if x1 > 0 & objs(index) > 0
        img = DrawThickColorRGBBox(img,  x1, y1, x2, y2, r, g, b, linethickness, xl, yl);
    end
end


function img = DrawGendersEllipses(img, ex0s, ey0s, ephis, eas, ebs, objs, gendertypes, bgenderwarnings, index)


sz = size(ex0s);
len = sz(2);

for j = 1:len
        

    
    if gendertypes(index, j) == 0 & bgenderwarnings(index) == 0 %female
        r = 250;
        g = 110;
        b = 110;
    elseif gendertypes(index, j) == 1 & bgenderwarnings(index) == 0 %male
        r = 110;
        g = 250;
        b = 110;
    else
        r = 255;
        g = 255;
        b = 255;
    end
    
    x0 = ex0s(index,j);
    y0 = ey0s(index,j);
    phi = ephis(index,j);
    ea = eas(index,j);
    eb = ebs(index,j);
    
    if x0 > 0 & objs(index) > 0
        img = DrawImgEllipseColor(img, x0, y0, ea, eb, phi, r, g, b);                    
    end
end



function img = DrawAreas(img, x1s, x2s, y1s, y2s, ax1s, ax2s, ay1s, ay2s, areascores, bestscoreindexes, bwarnings, bFemales, index)

r = 255;
g = 255;
b = 255;

linethickness = 1;

imgsz = size(img);
xl = imgsz(1);
yl = imgsz(2);

sz = size(ax1s);
nobjects = sz(2);
nareas = sz(3);

for j = 1:nobjects   
    x1 = x1s(index,j);
    x2 = x2s(index,j);
    y1 = y1s(index,j);
    y2 = y2s(index,j);   
    
    
    for k = 1:nareas                          
        
        bDraw = 1;
                        
        if bwarnings(index, j, k) ~= 0 | ax1s(index,j, k) == 0
                bDraw = 0;
        end
            
        if bDraw == 1
            ax1 = ax1s(index,j, k) + x1;
            ax2 = ax2s(index,j, k) + x1;
            ay1 = ay1s(index,j, k) + y1;
            ay2 = ay2s(index,j, k) + y1;
            
            if k == 1
                r = 250;
                g = 110;
                b = 110;
            elseif k == 2
                r = 110;
                g = 250;
                b = 100;
            elseif k == 3
                r = 110;
                g = 110;
                b = 250;
            elseif k == 4
                r = 240;
                g = 240;
                b = 130;    
            else
                r = 255;
                g = 255;
                b = 255;    
            end
    
            if x1 > 0
                img = DrawThickColorRGBBox(img,  ax1, ay1, ax2, ay2, r, g, b, linethickness, xl, yl);
            end
        end
    end
end




function img = DrawObjectsEllipses(img, ex0s, ey0s, ephis, eas, ebs, objs, index)

r = 255;
g = 255;
b = 255;
linethickness = 3;

imgsz = size(img);
xl = imgsz(1);
yl = imgsz(2);


sz = size(ex0s);
len = sz(2);

for j = 1:len
    
    x0 = ex0s(index,j);
    y0 = ey0s(index,j);
    phi = ephis(index,j);
    a = eas(index,j);
    b = ebs(index,j);
    
    if x0 > 0 & objs(index) > 0
        img = DrawImgEllipse(img, x0, y0, a, b, phi);                    
    end
end




function UpdateVideoProcessCheckBoxes(handles)

global scheck1;
global scheck2;
global scheck3;
global scheck4;
global scheck5;
global scheck6;
global scheck7;


set(handles.checkboxobjectdetection, 'Value', 1);
set(handles.checkboxpostprocessing, 'Value', 0);
set(handles.checkboxsegmentation, 'Value', 0);
set(handles.checkboxassignobjects, 'Value', 1);
set(handles.checkboxdetectareas, 'Value', 0);
set(handles.checkboxassigngender, 'Value', 0);
set(handles.checkboxpostprocessareas, 'Value', 0);


if ~isempty(scheck1)        
    set(handles.checkboxobjectdetection, 'Value', 0);
end

if ~isempty(scheck1) & ~isempty(scheck2)    
    set(handles.checkboxpostprocessing, 'Value', 0);
end

if ~isempty(scheck1) & ~isempty(scheck2) & ~isempty(scheck3)   
    set(handles.checkboxsegmentation, 'Value', 0);
end

if ~isempty(scheck1) & ~isempty(scheck2) & ~isempty(scheck3) & ~isempty(scheck4)    
    set(handles.checkboxassignobjects, 'Value', 0);    
end

if ~isempty(scheck5)    
    set(handles.checkboxdetectareas, 'Value', 0);
end

if ~isempty(scheck6)    
    set(handles.checkboxassigngender, 'Value', 0);
end

if ~isempty(scheck7)    
    set(handles.checkboxpostprocessareas, 'Value', 0);
end





function UpdateShowDetectionButtons(handles)
global inputfilefull;
global savefile;

global fdetectobjects;
global fpostprocess;
global fsegmentation;
global fassign;
global fdetectareas;
global fgenders;
global fareaspostprocess;


global scheck1;
global scheck2;
global scheck3;
global scheck4;
global scheck5;
global scheck6;
global scheck7;


set(handles.radiobuttonnone,'Enable','off');
set(handles.radiobuttonobjectdetection,'Enable','off');
set(handles.radiobuttonpostprocessing,'Enable','off');
set(handles.radiobuttonsegementation,'Enable','off');
set(handles.radiobuttonassignobjects,'Enable','off');

set(handles.checkboxshowdetectedareas,'Enable','off');
set(handles.checkboxshowassigngender,'Enable','off');
set(handles.checkboxshowpostprocessingareas,'Enable','off');



if isempty(savefile)
    savefile = 'videoprocessdata.mat';
end

if isempty(inputfilefull)
    load(savefile);
end


scheck1 = dir(fdetectobjects);
scheck2 = dir(fpostprocess);
scheck3 = dir(fsegmentation);
scheck4 = dir(fassign);
scheck5 = dir(fdetectareas);
scheck6 = dir(fgenders);
scheck7 = dir(fareaspostprocess);

if ~isempty(scheck1)
    set(handles.radiobuttonnone,'Enable','on');
    set(handles.radiobuttonobjectdetection,'Enable','on');
    
    %set(handles.checkboxobjectdetection, 'Value', 0);
end

if ~isempty(scheck2)% & ~isempty(scheck2)
    set(handles.radiobuttonpostprocessing,'Enable','on');  
    
    %set(handles.checkboxpostprocessing, 'Value', 0);
end

if ~isempty(scheck3) %& ~isempty(scheck2) & ~isempty(scheck3)
    set(handles.radiobuttonsegementation,'Enable','on'); 
    
    %set(handles.checkboxsegmentation, 'Value', 0);
end

if ~isempty(scheck4) %& ~isempty(scheck2) & ~isempty(scheck3) & ~isempty(scheck4)
    set(handles.radiobuttonassignobjects,'Enable','on');          
end

if ~isempty(scheck5)
    set(handles.checkboxshowdetectedareas,'Enable','on');    
    
end


if ~isempty(scheck6)
    set(handles.checkboxshowassigngender,'Enable','on');
end

if ~isempty(scheck7)
    set(handles.checkboxshowpostprocessingareas,'Enable','on');
end




function ProcessVideo(handles)

global inputfilefull;
global backgroundfilefull;
global bFrontView;
global calibsubtractfilefrontfull;
global calibsubtractfilesidefull;
global detectareasfilefull;
global savefile;

global selecttypesfile;

global fdetectobjects;
global fpostprocess;
global fsegmentation;
global fassign;
global fdetectareas;
global fgenders;
global fareaspostprocess;

global scheck5;
global scheck6;

global outputfilefull;


if isempty(savefile)
    savefile = 'videoprocessdata.mat';
end

     
if bFrontView == -1 | isempty(bFrontView)
    load(savefile);
    if bFrontView == -1 | isempty(bFrontView)
        errordlg('Camera view has not been set. Please set to front or side.');
        return
    end
end


if isempty(inputfilefull)
    load(savefile);
    if isempty(inputfilefull)
        errordlg('No video file appears to have been selected. Please check video file was selected before opening this dialog.');
        return
    end
end

if isempty(backgroundfilefull)
    load(savefile);
    if isempty(backgroundfilefull)
        errordlg('No background file appears to have been calculated. Please check background has been calculated for this video (file name will be [video name]_background.mat.');
        return
    end
end

scheck = dir(backgroundfilefull);

if isempty(scheck)
    s = 'Background file not found (name = ';
    s = strcat(s, backgroundfilefull);
    s = strcat(s, '). Please check that background has been calculated.');
    errordlg(s);
    return
end


if bFrontView == 0 | bFrontView == 1
else
    
    bfront = get(handles.radiobuttonfront, 'Value');
    bside = get(handles.radiobuttonside, 'Value');
    
    if bfront == 1
        bFrontView = 1;
    elseif bside == 1;
        bFrontView = 0;
    else
        errordlg('Please select view.');
        return
    end
end

if bFrontView == 1
    calibsubtractfile = calibsubtractfilefrontfull;
else    
    calibsubtractfile = calibsubtractfilesidefull;
end



if isempty(calibsubtractfile) 
    load(savefile);
    
    if bFrontView == 1
        calibsubtractfile = calibsubtractfilefrontfull;
    else
        calibsubtractfile = calibsubtractfilesidefull;
    end
    
    if isempty(calibsubtractfile) 
        errordlg('No calibration file has been selected for subtraction for this camera view. Please select a subtraction file from the main dialog or change the camera view.');
        return
    end
end

nstartframe = str2num(get(handles.editstart, 'String'));
nendframe = str2num(get(handles.editend, 'String'));
nfindobjs = str2num(get(handles.editobjects, 'String'));


bdrawsquare = get(handles.radiobuttondrawsquare, 'Value');
bdrawellipse = get(handles.radiobuttondrawellipse, 'Value');

sdraweveryframes = get(handles.editdrawframes, 'String');

nDrawEveryFrames = 100;
if ~isempty(sdraweveryframes)
    nDrawEveryFrames = str2num(sdraweveryframes);
end

nDrawFrameSelect = 0;

if bdrawsquare == 1
    nDrawFrameSelect = 1;
elseif bdrawellipse == 1
    nDrawFrameSelect = 2;
end


nfindmaxobjs = nfindobjs;






%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Start processing

% Detect Objects
% Post Process (remove any likely errors) 
% Object Segmentation
% Assign Objects
% Detect Areas



bDetectObjects = get(handles.checkboxobjectdetection, 'Value');
bPostProcess = get(handles.checkboxpostprocessing, 'Value');
bSegmentation = get(handles.checkboxsegmentation, 'Value');
bAssignObjects = get(handles.checkboxassignobjects, 'Value');
bDetectAreas = get(handles.checkboxdetectareas, 'Value');
bAssignGender = get(handles.checkboxassigngender, 'Value');
bDetectAreasPP = get(handles.checkboxpostprocessareas, 'Value');


flen = length(inputfilefull);
fout = inputfilefull(1:flen-4);


if isempty(fdetectobjects)
    fdetectobjects = strcat(fout, '_detectobjects.mat'); 
    fpostprocess = strcat(fout, '_postprocess.mat'); 
    fsegmentation = strcat(fout, '_objectsegmentation.mat'); 
    fassign = strcat(fout, '_assignobjects.mat'); 
    fdetectareas = strcat(fout, '_detectareas.mat'); 
    fgenders = strcat(fout, '_genders.mat'); 
    fareaspostprocess = strcat(fout, '_detectareaspp.mat');     
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Detect Objects
nprocess = 1;

if bDetectObjects == 1
    DetectObjects(nstartframe, nendframe, nfindobjs, nfindmaxobjs, inputfilefull, fdetectobjects, ...
                  backgroundfilefull, calibsubtractfile, handles, nDrawFrameSelect, nDrawEveryFrames);
    set(handles.textoutput, 'String', 'Finished processing video.');
    
    UpdateShowDetectionButtons(handles);
end


scheck = dir(fdetectobjects);
if isempty(scheck) 
    errordlg('Object detection is required before further processing steps can be applied. Please run first step (Detect Objects).');
    return;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Post Processing

set(handles.textoutput, 'String', 'Post processing...');

if bPostProcess == 1
    
    fin = fdetectobjects;
    fout = fpostprocess;
    
    PostProcess(fin, fout); %Remove any outliers (e.g. any objects that are too big/small)                            
    
    UpdateShowDetectionButtons(handles);
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Object Segmentation

if bSegmentation == 1
    
    scheck = dir(fpostprocess);
    
    if ~isempty(scheck)
        fin = fpostprocess;
    else
        fin = fdetectobjects;
    end
        
    fout = fsegmentation;
    
    %Seperate close objects
    set(handles.textoutput, 'String', 'Object Segmentation...');
    drawnow();
    
    nprocess = nprocess + 1;
    ObjectSegmentation(nfindobjs, inputfilefull, fin, fout, backgroundfilefull, calibsubtractfile, handles);
    
    
    UpdateShowDetectionButtons(handles);
end



if bAssignObjects == 1
    
    scheck = dir(fsegmentation);
    
    if ~isempty(scheck)
        fin = fsegmentation;
    else
        scheck = dir(fpostprocess);
        
        if ~isempty(scheck)
            fin = fpostprocess;
        else
            fin = fdetectobjects;
        end
    end
    
    fout = fassign;
    
    %Index objects and extrapolate any missing frames where possible
    set(handles.textoutput, 'String', 'Assigning objects...');
    drawnow();
    
    AssignObjects(fin, fout);
    
    %copy current data into final data file
    copyfile(fout, outputfilefull);
    
    UpdateShowDetectionButtons(handles);
    
    set(handles.textoutput, 'String', 'Finished object assignment.');
end





if bDetectAreas == 1 | bAssignGender == 1
    scheck = dir(fassign);
    if isempty(scheck) 
        errordlg('Assignment of objects is required before further processing steps can be applied. Please run Assign Objects step.');
        return;
    end
end



if bDetectAreas == 1
    %%Detect any areas (such as for identifying gender) if flag set
    %if ndetecttype > 0
        
        fin = fassign;
        fout = fdetectareas;
    
        %set(handles.textoutput, 'String', 'Area Detection...');
        nprocess = nprocess + 1;
           
        
        if isempty(detectareasfilefull)
            errordlg('No Detect Areas file selected. Please close this dialog, select a Detect Areas file in the main window, and open this dialog again.');
            return
        end
        
        DetectAreas(inputfilefull, fin, fout, calibsubtractfile, detectareasfilefull, handles);
        
        %copy current data into final data file
        copyfile(fout, outputfilefull);
    
        UpdateShowDetectionButtons(handles);
        %nprocess = nprocess + 1;
        %fout = PostProcessC(inputfilefull, nprocess); %Extrapolate frames for areas
    %end
end

if bAssignGender == 1
    fin = fdetectareas; 
    fout = fgenders;
    
    AssignGenders(fin, fout, handles);
    UpdateShowDetectionButtons(handles);        
    
    %copy current data into final data file
    copyfile(fout, outputfilefull);
end


if bDetectAreasPP == 1
    if ~isempty(scheck6)       
         fin = fgenders;
         fout = fareaspostprocess;
         
         bGenderFile = 1;
         DetectAreasPostProcess(fin, fout, bGenderFile); 
         
         UpdateShowDetectionButtons(handles);
         
         %copy current data into final data file
        copyfile(fout, outputfilefull);
        
    elseif ~isempty(scheck5)
         fin = fdetectareas; 
         fout = fareaspostprocess;
         
         bGenderFile = 0;
         
         DetectAreasPostProcess(fin, fout, bGenderFile);
         
         UpdateShowDetectionButtons(handles);
         
         %copy current data into final data file
         copyfile(fout, outputfilefull);
    else
        errordlg('Detect Areas - Post Process was selected but Detect Areas or Assign Genders file not found');
    end
end


set(handles.textoutput, 'String', 'Finished!');
    
    




% --- Executes just before iProcessVideo is made visible.
function iProcessVideo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to iProcessVideo (see VARARGIN)

% Choose default command line output for iProcessVideo
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes iProcessVideo wait for user response (see UIRESUME)
% uiwait(handles.figure1);

OnOpen(handles)



% --- Outputs from this function are returned to the command line.
function varargout = iProcessVideo_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;





function editstart_Callback(hObject, eventdata, handles)
% hObject    handle to editstart (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editstart as text
%        str2double(get(hObject,'String')) returns contents of editstart as a double


% --- Executes during object creation, after setting all properties.
function editstart_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editstart (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editend_Callback(hObject, eventdata, handles)
% hObject    handle to editend (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editend as text
%        str2double(get(hObject,'String')) returns contents of editend as a double


% --- Executes during object creation, after setting all properties.
function editend_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editend (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editobjects_Callback(hObject, eventdata, handles)
% hObject    handle to editobjects (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editobjects as text
%        str2double(get(hObject,'String')) returns contents of editobjects as a double


% --- Executes during object creation, after setting all properties.
function editobjects_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editobjects (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in radiobuttontemplate.
function radiobuttontemplate_Callback(hObject, eventdata, handles)
% hObject    handle to radiobuttontemplate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobuttontemplate


% --- Executes on button press in radiobuttoncluster.
function radiobuttoncluster_Callback(hObject, eventdata, handles)
% hObject    handle to radiobuttoncluster (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobuttoncluster



% --- Executes on slider movement.
function sliderframe_Callback(hObject, eventdata, handles)
% hObject    handle to sliderframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

SliderGotoFrame(handles);

% --- Executes during object creation, after setting all properties.
function sliderframe_CreateFcn(hObject, eventdata, handles)
% hObject    handle to sliderframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


% --- Executes on button press in pushbuttongo.
function pushbuttongo_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttongo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ButtonGotoFrame(handles)




function editframe_Callback(hObject, eventdata, handles)
% hObject    handle to editframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editframe as text
%        str2double(get(hObject,'String')) returns contents of editframe as a double


% --- Executes during object creation, after setting all properties.
function editframe_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbuttonstartframe.
function pushbuttonstartframe_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonstartframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global ncurrentframe;

set(handles.editstart, 'String', num2str(ncurrentframe));

% --- Executes on button press in pushbuttonendframe.
function pushbuttonendframe_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonendframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global ncurrentframe;

set(handles.editend, 'String', num2str(ncurrentframe));




% --- Executes on button press in pushbuttoncancel.
function pushbuttoncancel_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttoncancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

close();


% --- Executes on button press in pushbuttonprocessvideo.
function pushbuttonprocessvideo_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonprocessvideo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.textoutput, 'String', 'Initializing...');
drawnow()
ProcessVideo(handles)


% --- Executes when selected object is changed in uipanelview.
function uipanelview_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanelview 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)


global bFrontView;

bFrontView = get(handles.radiobuttonfront, 'Value');



function editdrawframes_Callback(hObject, eventdata, handles)
% hObject    handle to editdrawframes (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editdrawframes as text
%        str2double(get(hObject,'String')) returns contents of editdrawframes as a double


% --- Executes during object creation, after setting all properties.
function editdrawframes_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editdrawframes (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in checkboxshowdetectedareas.
function checkboxshowdetectedareas_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxshowdetectedareas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxshowdetectedareas

GotoFrame(handles);


% --- Executes on button press in checkboxshowassigngender.
function checkboxshowassigngender_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxshowassigngender (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxshowassigngender

GotoFrame(handles);

% --- Executes on button press in checkboxobjectdetection.
function checkboxobjectdetection_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxobjectdetection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxobjectdetection


% --- Executes on button press in checkboxpostprocessing.
function checkboxpostprocessing_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxpostprocessing (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxpostprocessing


% --- Executes on button press in checkboxassignobjects.
function checkboxassignobjects_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxassignobjects (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxassignobjects


% --- Executes on button press in checkboxsegmentation.
function checkboxsegmentation_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxsegmentation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxsegmentation


% --- Executes on button press in checkboxassigngender.
function checkboxassigngender_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxassigngender (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxassigngender


% --- Executes on button press in checkboxdetectareas.
function checkboxdetectareas_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxdetectareas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxdetectareas









% --- Executes when selected object is changed in uipanelshowobjectdetection.
function uipanelshowobjectdetection_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanelshowobjectdetection 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)

GotoFrame(handles);


% --- Executes when selected object is changed in uipaneldraw.
function uipaneldraw_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipaneldraw 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)

GotoFrame(handles);


% --- Executes on button press in pushbuttonback.
function pushbuttonback_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonback (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global ncurrentframe;

ncurrentframe = ncurrentframe - 1;

if ncurrentframe < 1
    ncurrentframe = 1;
end


set(handles.editframe, 'String', num2str(ncurrentframe));

ButtonGotoFrame(handles)








% --- Executes on button press in pushbuttonfwd.
function pushbuttonfwd_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonfwd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global totalframes; 
global ncurrentframe;

ncurrentframe = ncurrentframe + 1;

if ncurrentframe > totalframes
    ncurrentframe = totalframes;
end

set(handles.editframe, 'String', num2str(ncurrentframe));

ButtonGotoFrame(handles)


% --- Executes on button press in checkboxpostprocessareas.
function checkboxpostprocessareas_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxpostprocessareas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxpostprocessareas


% --- Executes on button press in checkboxshowpostprocessingareas.
function checkboxshowpostprocessingareas_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxshowpostprocessingareas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxshowpostprocessingareas

GotoFrame(handles);



function editvideofrom_Callback(hObject, eventdata, handles)
% hObject    handle to editvideofrom (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editvideofrom as text
%        str2double(get(hObject,'String')) returns contents of editvideofrom as a double


% --- Executes during object creation, after setting all properties.
function editvideofrom_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editvideofrom (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editvideoto_Callback(hObject, eventdata, handles)
% hObject    handle to editvideoto (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editvideoto as text
%        str2double(get(hObject,'String')) returns contents of editvideoto as a double


% --- Executes during object creation, after setting all properties.
function editvideoto_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editvideoto (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbuttonvideooutput.
function pushbuttonvideooutput_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonvideooutput (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global totalframes;
global v;

global fdetectobjects;
global fpostprocess;
global fsegmentation;
global fassign;
global fdetectareas;
global fgenders;
global fareaspostprocess;

global scheck1;
global scheck2;
global scheck3;
global scheck4;
global scheck5;
global scheck6;
global scheck7;

global inputfilefull;

if isempty(v)
    
    if isempty(inputfilefull) 
        load('videoprocessdata.mat');
    end
        
    if ~isempty(inputfilefull)
        scheck = dir(inputfilefull);
        
        if ~isempty(scheck)
            v = mmreader(inputfilefull);
            totalframes = v.NumberOfFrames;
            ncurrentframe = 1;
            
            set(handles.editframe, 'String', num2str(ncurrentframe));
            set(handles.textframes, 'String', num2str(totalframes));
        end
    end
end



rbnone = get(handles.radiobuttonnone, 'Value');
rbobjdetect = get(handles.radiobuttonobjectdetection,'Value');
rbpostprocess = get(handles.radiobuttonpostprocessing,'Value');
rbsegment = get(handles.radiobuttonsegementation,'Value');
rbassignobj = get(handles.radiobuttonassignobjects,'Value');

cbdetectareas = get(handles.checkboxshowdetectedareas,'Value');
cbgenderssign = get(handles.checkboxshowassigngender,'Value');
cbdetectareaspp = get(handles.checkboxshowpostprocessingareas,'Value');

rbsquares = get(handles.radiobuttondrawsquares,'Value');
rbellipses = get(handles.radiobuttondrawellipses,'Value');

nvideostart = str2num(get(handles.editvideofrom, 'String'));
nvideoend = str2num(get(handles.editvideoto, 'String'));


bdrawellipse = 1;
if rbsquares == 1
    bdrawellipse = 0;
end
    

if isempty(inputfilefull)
    errordlg('Please specify a video file in the main window and re-open this dialog'); 
    return
end

flen = length(inputfilefull);
f = inputfilefull(1:flen-4);
fvideoout = strcat(f, '_vout.avi');

sout = fvideoout;
sout = strcat(sout, ' generated');


set(handles.textoutput, 'String', '');

if rbnone == 1 & cbgenderssign == 0
    
    if nvideostart > 0 & nvideostart <= totalframes & nvideoend > 0 & nvideoend <= totalframes 
        voutputraw(inputfilefull, fvideoout, nvideostart, nvideoend);
        set(handles.textoutput, 'String', sout);
    else
        errordlg('Video to/from range is outside of the length of the original video. Please select a suitable range.');
    end
    
    return
end

if ~isempty(scheck1) 
    load(fdetectobjects); %load to get nstartframe and nendframe
else
    errordlg('No data files found');
    return
end


if nvideostart < nstartframe | nvideostart > nendframe | nvideoend < nstartframe | nvideoend > nendframe
    errordlg('Video to/from range is outside of data range. Please select a suitable range.');
    return
end


nvideostart = nvideostart-nstartframe+1;
nvideoend = nvideoend-nstartframe+1;


if rbobjdetect == 1 & cbgenderssign == 0
    if ~isempty(scheck1)                
        voutput(inputfilefull, fvideoout, fdetectobjects, nvideostart, nvideoend, bdrawellipse);        
    end
elseif rbpostprocess == 1 & cbgenderssign == 0
    if ~isempty(scheck2)
        
        voutput(inputfilefull, fvideoout, fpostprocess, nvideostart, nvideoend, bdrawellipse);                      
    end
elseif rbsegment == 1 & cbgenderssign == 0
    if ~isempty(scheck3)
                
        voutput(inputfilefull, fvideoout, fsegmentation, nvideostart, nvideoend, bdrawellipse);                           
    end
elseif rbassignobj == 1 & cbgenderssign == 0 & cbdetectareas == 0 & cbdetectareaspp == 0
    if ~isempty(scheck4)
                      
        bdrawareas = 0;
        voutputassigned(inputfilefull, fvideoout, fassign, nvideostart, nvideoend, bdrawellipse, bdrawareas);                                   
    end    
elseif cbgenderssign == 0 & cbdetectareas == 1 & cbdetectareaspp == 0        
    
    if ~isempty(scheck5)                 
        bdrawareas = 1;
        voutputassigned(inputfilefull, fvideoout, fdetectareas, nvideostart, nvideoend, bdrawellipse, bdrawareas);      
    end    
elseif cbgenderssign == 1 & cbdetectareas == 0 & cbdetectareaspp == 0        
    
    if ~isempty(scheck6)                 
        bdrawareas = 0;
        voutputgender(inputfilefull, fvideoout, fgenders, nvideostart, nvideoend, bdrawellipse, bdrawareas);
    end
elseif cbgenderssign == 1 & cbdetectareas == 1 & cbdetectareaspp == 0
        
    if ~isempty(scheck6)             
        bdrawareas = 1;
        voutputgender(inputfilefull, fvideoout, fgenders, nvideostart, nvideoend, bdrawellipse, bdrawareas);        
    end
elseif cbgenderssign == 1 & cbdetectareaspp == 1
        
    if ~isempty(scheck7)                 
        bdrawareas = 1;
        voutputgender(inputfilefull, fvideoout, fareaspostprocess, nvideostart, nvideoend, bdrawellipse, bdrawareas);        
    end                
elseif cbgenderssign == 0 & cbdetectareaspp == 1
        
    if ~isempty(scheck7)                
        bdrawareas = 1;
        voutputassigned(inputfilefull, fvideoout, fareaspostprocess, nvideostart, nvideoend, bdrawellipse, bdrawareas);
    end        
else
    return
end

set(handles.textoutput, 'String', sout);




function editalignmentframe_Callback(hObject, eventdata, handles)
% hObject    handle to editalignmentframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editalignmentframe as text
%        str2double(get(hObject,'String')) returns contents of editalignmentframe as a double


% --- Executes during object creation, after setting all properties.
function editalignmentframe_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editalignmentframe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
